/*
	This file is part of the JKTest
    Copyright (C) 2008 Royce Y. Feng <ryfeng@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package JKPanels;

import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.awt.Dimension;

import jktest.JKMainPanel;
import jktest.JKMainGui;
import jktest.JMultilineLabel;
import jktest.JKButton;

/**
 * 
 * Panel Class containing all elements of the Sound Test
 * 
 * @author Royce Feng
 */
public class SoundPanel extends JKMainPanel {

    private PassFailPanel passFail;
    
    /**
     * 
     * Main Constructor for SoundPanel. Creates a multiline label with instructions
     * as well as the three main buttons: Start test, Pass, Fail.
     * 
     * @param _parent The Parent Class (for communication)
     */
    public SoundPanel ( JKMainGui _parent ) {
        super(_parent);
        JMultilineLabel instructions = new JMultilineLabel();
        instructions.setMaxWidth(500);
        instructions.setText("After you click the button, JKTest will try to load a media file from your " +
                "system directory. If you hear a sound, it works!");
        this.add(instructions);
        JKButton button = new JKButton(this,"Sound");
        button.setPreferredSize(new Dimension(200,25));
        this.add( button );        
        passFail = new PassFailPanel(this);
        passFail.setPreferredSize(new Dimension(500,25));
        this.add(passFail);
    }
    
    /**
     * 
     * Returns the name of the panel
     * 
     * @return The name of the panel
     */
    @Override
    public String getName() {
        return "Sound";
    }

    private class SoundRunner implements Runnable {

        private String filename;

        public SoundRunner(String _filename) {
            filename = _filename;
        }

        public void run() {
            File soundFile = new File(filename);
            if (!soundFile.exists()) {
                System.err.println("Wave file not found: " + filename);
                return;
            }
            AudioInputStream audioInputStream = null;
            try {
                audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            } catch (UnsupportedAudioFileException e1) {
                JOptionPane.showMessageDialog(null, "Sound could not be played. Please rerun the test.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            } catch (IOException e1) {
                JOptionPane.showMessageDialog(null, "Sound could not be played. Please rerun the test.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            AudioFormat format = audioInputStream.getFormat();
            SourceDataLine auline = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            try {
                auline = (SourceDataLine) AudioSystem.getLine(info);
                auline.open(format);
            } catch (LineUnavailableException e) {
                JOptionPane.showMessageDialog(null, "Sound could not be played. Please rerun the test.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Sound could not be played. Please rerun the test.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            auline.start();
            int nBytesRead = 0;
            byte[] abData = new byte[524288];
            try {
                while (nBytesRead != -1) {
                    nBytesRead = audioInputStream.read(abData, 0, abData.length);
                    if (nBytesRead >= 0) {
                        auline.write(abData, 0, nBytesRead);
                    }
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Sound could not be played. Please rerun the test.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            } finally {
                auline.drain();
                auline.close();
            }
        }

    }
    
    /**
     * 
     * Handles button clicks. Pass/fail gets sent to parent while the test is run
     * when the test button is clicked.
     * 
     * @param source Button source (usually the button text)
     */
    public void ButtonClicked( String source ) {
        if ( source.equals("Pass") ) {
            getThisParent().valChanged(this.getName(), true);
            getThisParent().incPanel();
        } else if ( source.equals("Fail") ) {
            getThisParent().valChanged(this.getName(), false);
            getThisParent().incPanel();
        } else {
            String osName = System.getProperty("os.name");
            if ( osName.toUpperCase().startsWith("WINDOWS") ) {
                String root = System.getenv("SystemRoot");
                root += "\\media\\";
                File f = new File(root);
                String[] children = f.list();
                int n = (int) (Math.random() * children.length);
                while ( children[n].indexOf(".wav") == -1 )
                    n = (int) (Math.random() * children.length);
                Thread t = new Thread(new SoundRunner(root+children[n]));
                t.start();
            } else {
                JOptionPane.showMessageDialog(this, osName + "detected as operating system.", "Operating System not Windows", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
}
